import scrapy
import time
import json
from pku_data.items import ClassroomData


def timestamp_to_time(timestamp):
    time_struct = time.localtime(timestamp)
    return time.strftime("%Y-%m-%d", time_struct)


class PkuPortalSpider(scrapy.Spider):
    name = "pku_portal"
    allowed_domains = ["pku.edu.cn"]
    # class_buildings=['二教']
    class_buildings = ["一教", "二教", "三教", "理教", "文史", "地学"]
    times = ["今天"]
    # times=['今天','明天','后天']
    base_url = (
        "https://wxsp.pku.edu.cn/portal2017/publicsearch/classroom/retrClassRoomFree.do"
    )

    def start_requests(self):
        for cur_time in self.times:
            for building in self.class_buildings:
                data = {
                    "buildingName": building,
                    "time": cur_time,
                }
                yield scrapy.FormRequest(
                    url=self.base_url,
                    formdata=data,
                    callback=self.parse,
                    meta={"buildingName": building, "time": cur_time},
                )

    def parse(self, response, **kwargs):
        data = json.loads(response.body)
        crawl_time = response.meta["time"]
        building_name = response.meta["buildingName"]
        if crawl_time == "今天":
            cur_time = timestamp_to_time(time.time())
        elif crawl_time == "明天":
            cur_time = timestamp_to_time(time.time() + 24 * 60 * 60)
        else:
            cur_time = timestamp_to_time(time.time() + 2 * 24 * 60 * 60)
        item = ClassroomData()
        item["building_name"] = building_name
        item["crawl_time"] = cur_time
        item["classroom_data"] = data["rows"]
        yield item
